from PIL import Image
import os
import shutil
import tkinter as tk
from tkinter import filedialog, messagebox, ttk
from tkinter.ttk import Progressbar

def convert_images():
    input_path = input_entry.get()
    save_path = output_entry.get()
    
    if not input_path or not save_path:
        messagebox.showerror("错误", "请输入输入路径和输出路径")
        return
    
    try:
        # 获取文件列表
        files = [f for f in os.listdir(input_path) if f.lower().endswith(('.bmp', '.jpg', '.jpeg', '.png'))]
        total_files = len(files)
        
        if total_files == 0:
            messagebox.showinfo("信息", "没有找到可处理的图片文件")
            return
        
        # 设置进度条最大值
        progress_bar['maximum'] = total_files
        progress_bar['value'] = 0
        progress_label.config(text=f"0/{total_files}")
        root.update()  # 更新界面
        
        os.makedirs(save_path, exist_ok=True)
        
        for i, file in enumerate(files, 1):
            file_path = os.path.join(input_path, file)
            output_file = os.path.splitext(file)[0] + '.jpg'  # 统一改为.jpg后缀
            
            try:
                # 打开图片并保存为JPG格式
                img = Image.open(file_path)
                if img.mode == 'RGBA':
                    # 如果图片有透明通道，先转换为RGB
                    img = img.convert('RGB')
                img.save(os.path.join(save_path, output_file), quality=95)
                
                # 更新进度
                progress_bar['value'] = i
                progress_label.config(text=f"{i}/{total_files} - 正在处理: {file}")
                root.update()  # 更新界面
                
            except Exception as e:
                print(f"处理文件 {file} 时出错: {str(e)}")
                continue
        
        messagebox.showinfo("完成", f"成功处理{total_files}张图片!")
        
        # 重置进度条
        progress_bar['value'] = 0
        progress_label.config(text="准备就绪")
        
    except Exception as e:
        messagebox.showerror("错误", f"处理过程中出现错误:\n{str(e)}")
        progress_bar['value'] = 0
        progress_label.config(text="发生错误")

def browse_input():
    folder = filedialog.askdirectory()
    if folder:
        input_entry.delete(0, tk.END)
        input_entry.insert(0, folder)

def browse_output():
    folder = filedialog.askdirectory()
    if folder:
        output_entry.delete(0, tk.END)
        output_entry.insert(0, folder)

# 创建主窗口
root = tk.Tk()
root.title("图片格式转换工具")

# 输入路径
tk.Label(root, text="输入路径:").grid(row=0, column=0, padx=5, pady=5, sticky="e")
input_entry = tk.Entry(root, width=50)
input_entry.grid(row=0, column=1, padx=5, pady=5)
tk.Button(root, text="浏览...", command=browse_input).grid(row=0, column=2, padx=5, pady=5)

# 输出路径
tk.Label(root, text="输出路径:").grid(row=1, column=0, padx=5, pady=5, sticky="e")
output_entry = tk.Entry(root, width=50)
output_entry.grid(row=1, column=1, padx=5, pady=5)
tk.Button(root, text="浏览...", command=browse_output).grid(row=1, column=2, padx=5, pady=5)

# 转换按钮
tk.Button(root, text="开始转换", command=convert_images).grid(row=2, column=1, pady=10)

# 进度条
progress_frame = tk.Frame(root)
progress_frame.grid(row=3, column=0, columnspan=3, padx=10, pady=5, sticky="ew")

progress_bar = Progressbar(progress_frame, orient="horizontal", length=300, mode="determinate")
progress_bar.pack(fill="x", expand=True)

progress_label = tk.Label(progress_frame, text="准备就绪")
progress_label.pack()

# 运行主循环
root.mainloop()